package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.vo.Subject;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.util.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author sen
 * @since 2024-01-22
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    //添加课程分类
    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        //文件输入流
        try {
            InputStream in = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(in, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Subject> getAllSubject() {
        List<Subject> subjects = new ArrayList<>();

        //查询所有数据
        List<EduSubject> all = baseMapper.selectList(null);

        //查询所有的一级区域
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", 0);
        List<EduSubject> oneEduSubjectList = baseMapper.selectList(wrapper);

        for (EduSubject eduSubject : oneEduSubjectList) {
            Subject subject = new Subject();
            BeanUtils.copyProperties(eduSubject, subject);
            //查询子节点
            List<Subject> children = findChildrens(eduSubject.getId(), all);
            subject.setChildren(children);

            subjects.add(subject);
        }
        return subjects;
    }

    public List<Subject> findChildrens(String id, List<EduSubject> all) {
        List<Subject> childList = new ArrayList<>();
        if (id != null && all != null) {
            for (EduSubject eduSubject : all) {
                if (Objects.equals(eduSubject.getParentId(), id)) {
                    Subject subject1 = new Subject();
                    BeanUtils.copyProperties(eduSubject, subject1);
                    subject1.setChildren(findChildrens(subject1.getId(), all));
                    childList.add(subject1);
                }
            }
        }
        return childList;
    }
}
